from utils.log import logger
import requests
import random
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

def build_headers(referer, cookie=''):
    if not referer:
        referer = 'https://www.baidu.com'
    user_agents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
        '(KHTMxL, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/68.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) '
        'Gecko/20100101 Firefox/68.0',
        'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/68.0'
    ]
    ua = random.choice(user_agents)
    headers = {
        'Accept': 'text/html, application/xhtml+xml, image/jxr, */*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
        'Connection': 'Keep-Alive',
        'Cookie': cookie,
        'Referer': referer,
        'User-Agent': ua
    }
    return headers


def get_req(url, referer, redirect, is_json=False, t=0):
    """Send a request if not 302 error,Maximum request 20 times """
    if t > 20:
        logger.error("【失败】请求超过20次 {}".format(url))
        raise Exception(print("请求错误尝试超过20次，自动退出"))

    resp = requests.get(url, headers=build_headers(referer), verify=False, timeout=10,
                        allow_redirects=redirect,
                        )

    if resp.status_code == 200:
        res = resp.text
        return res
    elif resp.status_code == 302:
        logger.error("【风险校验】需要更新Cookie {}".format(url))
        return None
    else:
        return get_req(url, referer, redirect, is_json, t + 1)
